# -*- coding: utf-8 -*-

#使用Playwright Python框架监听并优雅处理JavaScript弹出的alert、prompt和confirm对话框。
# 通过设置dialog事件监听器，可以避免页面因未处理对话框而冻结，同时展示如何获取和响应对话框的内容。

from playwright.sync_api import sync_playwright

def handle_dialog(dialog):
    """监听后处理"""
    print(dialog.message)
    dialog.dismiss()


def run(playwright):
    chromium = playwright.chromium
    browser = chromium.launch(headless=False, slow_mo=3000)
    page = browser.new_page()
    #监听到 dialog事件，  监听器必须dialog.accept()或dialog.dismiss()，否则页面将冻结等待对话框，并且单击等操作将永远不会完成
    page.on("dialog", handle_dialog)
    page.evaluate("alert('hello world')")
    browser.close()


if __name__ == '__main__':
    with sync_playwright() as playwright:
        run(playwright)





